package com.base;

import com.immomo.mcf.util.JsonUtils;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

/**
 * @author: sun.hongliang
 * @create: 2019/08/09 11:15
 */
public class ReferenceTest {
    public static void main(String[] args) {
        testWeakRefrence();
//        testSoftRefrence();
//        ReferenceQueue<Apple> queue = new ReferenceQueue<>();
//        PhantomReference phantomReference = new PhantomReference(new Apple("ref"), queue);
//        System.out.println(queue.poll());
//        System.out.println("======");
//        System.out.println(queue.poll());
//        System.gc();
//        System.out.println(queue.poll());
    }

    private static void testSoftRefrence() {
        SoftReference softReference = new SoftReference(new Apple("qq"));
        System.out.println(softReference.get());
        System.out.println("======");
        System.gc();
        System.out.println(softReference.get());
    }

    private static void testWeakRefrence() {
        ReferenceQueue<Apple> queue = new ReferenceQueue<>();
        Salad salad = new Salad(new Apple("红富士"));
        WeakReference<Apple> weakReference = new WeakReference<>(new Apple("hh"), queue);
        System.out.println(weakReference.get());
        //通过WeakReference的get()方法获取Apple
        System.out.println("Apple:" + salad.get());
        System.out.println(queue.poll() + "  b");
        System.gc();
        //如果为空，代表被回收了
        if (salad.get() == null) {
            System.out.println("clear Apple。");
        }
        System.out.println(queue.poll() + "   a");
    }
}

class Apple {
    private String name;

    public Apple(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("Apple： " + name + " finalize。");
    }

    @Override
    public String toString() {
        return JsonUtils.toJSON(this);
    }
}

class Salad extends WeakReference<Apple> {
    public Salad(Apple referent) {
        super(referent);
    }
}
